//
//  LoginViewController.m
//  何五路
//
//  Created by _ADY on 15/6/25.
//  Copyright (c) 2015年 _ADY. All rights reserved.
//

#import "LoginViewController.h"
#import "zhViewController.h"
#import "zcViewController.h"

@interface LoginViewController ()

@end

static LoadingView *loading = nil;
@implementation LoginViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = @"登录";
        self.view.backgroundColor = bgColor;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.navigationItem.backBarButtonItem = item;
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(leftAction)];

    
    mTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, screenMySize.size.width, 240+64+20) style:UITableViewStyleGrouped];
    mTableView.delegate = self;
    mTableView.dataSource = self;
    mTableView.scrollEnabled = NO;
    mTableView.sectionHeaderHeight = 0.0;
    mTableView.sectionFooterHeight = 0.0;
    mTableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:mTableView];
    
    
    bgButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [bgButton setFrame:CGRectMake(20, mTableView.frame.size.height+mTableView.frame.origin.y, screenMySize.size.width-40, 40)];
    [bgButton setTitle:@"登录" forState:UIControlStateNormal];
    [bgButton addTarget:self action:@selector(loginAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:bgButton];
    [self PtButton];
    
    UIButton *zcButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [zcButton setFrame:CGRectMake(20, mTableView.frame.size.height+mTableView.frame.origin.y+50, 100, 25)];
    [zcButton setTitle:@"手机快速注册" forState:UIControlStateNormal];
    [zcButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [zcButton addTarget:self action:@selector(zcAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:zcButton];
    
    UIButton *zhButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [zhButton setFrame:CGRectMake(screenMySize.size.width-80, mTableView.frame.size.height+mTableView.frame.origin.y+50, 60, 25)];
    [zhButton setTitle:@"找回密码" forState:UIControlStateNormal];
    [zhButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [zhButton addTarget:self action:@selector(zhAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:zhButton];
    
    [self barView];
}

-(void)barView
{
    UIView *bView = [[UIView alloc] initWithFrame:CGRectMake(0, screenMySize.size.height-50, screenMySize.size.width, 50)];
    bView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bView];
    
    UIView *b1View = [[UIView alloc] initWithFrame:CGRectMake(screenMySize.size.width/3, screenMySize.size.height-50+10, .5, 30)];
    b1View.backgroundColor = [UIColor colorWithWhite:.8 alpha:1];
    [self.view addSubview:b1View];
    
    UIView *b2View = [[UIView alloc] initWithFrame:CGRectMake(screenMySize.size.width*2/3, screenMySize.size.height-50+10, .5, 30)];
    b2View.backgroundColor = [UIColor colorWithWhite:.8 alpha:1];
    [self.view addSubview:b2View];
    
    NSArray *tArray = [NSArray arrayWithObjects:@"微信登录",@"QQ登录",@"其他方式登录", nil];
    for (int i = 0; i < 3; i ++)
    {
        NSString *title = [tArray objectAtIndex:i];
        UIImage *imageD = nil;
        if (i == 0)
            imageD = [UIImage imageNamed:@"wx"];
        else if (i == 1)
            imageD = [UIImage imageNamed:@"qq"];
        
        UIButton *inButton = [UIButton buttonWithType:UIButtonTypeCustom];
        CGRect frame = CGRectMake(0,0, screenMySize.size.width/3, 50);
        [inButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        inButton.titleLabel.font = [UIFont fontWithName:@"Arial" size:labelSize-1];
        [inButton setTitle:title forState:UIControlStateNormal];
        
        [inButton setFrame:frame];
        [inButton setTitleEdgeInsets:UIEdgeInsetsMake(0, imageD.size.width, 0, 0)];
        [inButton setImageEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
        
        [inButton setImage:imageD forState:UIControlStateNormal];

        inButton.center = CGPointMake(screenMySize.size.width*i/3+screenMySize.size.width/6, 50/2);
        inButton.tag = 10+i;
        [inButton addTarget:self action:@selector(aInBction:) forControlEvents:UIControlEventTouchUpInside];
        [bView addSubview:inButton];
    }
    
}
-(void)aInBction:(id)sender
{
//    int topType = ((UIButton*)sender).tag - 10;
}

-(void)loginAction
{
    loading = [[LoadingView alloc] initWithFrame:self.view.frame];
    [self.view addSubview:loading];
    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
    
    NSMutableDictionary *postDic = [[NSMutableDictionary alloc] init];
    [postDic setObject:account.text forKey:@"username"];
    [postDic setObject:password.text forKey:@"password"];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        NSDictionary *ret = [SendService Login:postDic];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (ret !=nil)
            {
                NSLog(@"ret %@",ret);
                [loading closeLoading];
                if ([[ret objectForKey:@"Result"] isEqualToString:@"success"])
                {
                    [SendService setUserAccount:account.text];
                    [SendService setPassword:password.text];
                    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isLoginKey"];
                    
                    [[NSNotificationCenter defaultCenter] postNotificationName:kTreatedCompleteNotification object:self];
//                    [self.navigationController popViewControllerAnimated:YES];
                    [self leftAction];
                }
                else
                {
                    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isLoginKey"];
                    [SendService alerViewMessage:[ret objectForKey:@"Message"]];
                }
            }
            
        });
    });
}

-(void)zcAction
{
    zcViewController *browser = [[zcViewController alloc] init];
    browser.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:browser animated:YES];
}

-(void)zhAction
{
    zhViewController *browser = [[zhViewController alloc] init];
    browser.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:browser animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -
#pragma mark Table View DataSource

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    if (section == 0)
        return 0.001;
    return 10;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
        return 1;
    return 2;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
        return 142*screenMySize.size.width/320;
    return 40;
}

- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        aTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        aTableView.showsVerticalScrollIndicator = NO;
    }
    int i = (int)[[cell.contentView subviews] count] - 1;
    for(;i >= 0 ; i--)
    {
        [[[cell.contentView subviews] objectAtIndex:i] removeFromSuperview];
    }
    cell.backgroundColor = [UIColor whiteColor];
    
    if (indexPath.section == 0)
        return [self mCell:cell aCTableView:aTableView cellForRowAtIndexPath:indexPath];
    else if (indexPath.section == 1)
        return [self mCell:cell bCTableView:aTableView cellForRowAtIndexPath:indexPath];
    // Configure the cell...
    return cell;
}

- (UITableViewCell *)mCell:(UITableViewCell*)cell aCTableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIImageView *bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0, screenMySize.size.width, 142*screenMySize.size.width/320)];
    [bgImageView setImage:[UIImage imageNamed:@"user_bg"]];
    [cell.contentView addSubview:bgImageView];
    
    return cell;
}

- (UITableViewCell *)mCell:(UITableViewCell*)cell bCTableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.textLabel.text = @"账号:";
    if (indexPath.row==1)
        cell.textLabel.text = @"密码:";
    cell.textLabel.textAlignment = 0;
    cell.textLabel.textColor = [UIColor blackColor];
    
    if (indexPath.row == 1)
    {
        password = [[UITextField alloc] initWithFrame:CGRectMake(60, 0, screenMySize.size.width-120, 40)];
        password.backgroundColor = [UIColor clearColor];
        [password setFont:[UIFont systemFontOfSize:labelSize]];
        password.returnKeyType = UIReturnKeyGo;
        [password setPlaceholder:@"请输入密码"];
        [password setClearButtonMode:UITextFieldViewModeWhileEditing];
        password.delegate = self;
//        password.text = @"123";
        password.text = [SendService password];
        [cell.contentView addSubview:password];
        
        UISwitch *swi1=[[UISwitch alloc]init];
        swi1.frame=CGRectMake(screenMySize.size.width-60, 5, 60, 30);
        swi1.onTintColor=[UIColor redColor];
        if (![[NSUserDefaults standardUserDefaults] boolForKey:@"passwordKey"])
        {
            [swi1 setOn:NO animated:YES];
            password.secureTextEntry = YES;
        }
        else
        {
            [swi1 setOn:YES animated:YES];
            password.secureTextEntry = NO;
        }
        [swi1 addTarget:self action:@selector(getValue:) forControlEvents:UIControlEventValueChanged];
        [cell.contentView addSubview:swi1];
        
    }
    else
    {
        account = [[UITextField alloc] initWithFrame:CGRectMake(60, 0, screenMySize.size.width-120, 40)];
        account.backgroundColor = [UIColor clearColor];
        [account setFont:[UIFont systemFontOfSize:labelSize]];
        account.returnKeyType = UIReturnKeyNext;
        [account setClearButtonMode:UITextFieldViewModeWhileEditing];
        account.delegate = self;
//        account.text = @"admin@hewulu.com";
        account.text = [SendService userAccount];
        [account setPlaceholder:@"请输入账号"];
        [cell.contentView addSubview:account];
        
    }
    [self PtButton];

    return cell;
}

-(void)getValue:(id)sender{
    UISwitch *swi2=(UISwitch *)sender;
    
    [[NSUserDefaults standardUserDefaults] setBool:swi2.isOn forKey:@"passwordKey"];
    password.secureTextEntry = !swi2.isOn;
}

#pragma mark -
#pragma mark UITextFieldDelegate
//限制输入长度 by zwb 2011.9.6
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
     NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (textField == password) {
        if (range.location > 15){
            
            [SendService alerViewMessage:mPasswordLong];
            password.text = [textField.text substringToIndex:[textField.text length] - 1];
            return NO;
        }
        
    }
    else if (textField == account)
    {
        if (![[SendService userAccount] isEqualToString:text]) {
            password.text = @"";
        }
        else
        {
            password.text = [SendService password];
        }
    }
    
    if (text.length!=0)
    {
        [bgButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        bgButton.enabled = YES;
        [bgButton setBackgroundImage:[UIImage imageNamed:@"enButtons"] forState:UIControlStateNormal];
    }
    else
    {
        [bgButton setTitleColor:[UIColor colorWithRed:205/255.0 green:205/255.0 blue:205/255.0 alpha:1] forState:UIControlStateNormal];
        bgButton.enabled = NO;
        [bgButton setBackgroundImage:[UIImage imageNamed:@"enButton"] forState:UIControlStateNormal];
    }
    
    return YES;
    
}


- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    [textField resignFirstResponder];
    [mTableView setContentOffset:CGPointMake(0, 90) animated:YES];
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == account) {
        [password becomeFirstResponder];
    }
    else
    {
        [textField resignFirstResponder];
        [mTableView setContentOffset:CGPointMake(0, -60) animated:YES];
    }
    [self PtButton];

    return YES;
}

-(void)PtButton
{
    if (account.text.length!=0 &&password.text.length!=0)
    {
        [bgButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        bgButton.enabled = YES;
        [bgButton setBackgroundImage:[UIImage imageNamed:@"enButtons"] forState:UIControlStateNormal];
    }
    else
    {
        [bgButton setTitleColor:[UIColor colorWithRed:205/255.0 green:205/255.0 blue:205/255.0 alpha:1] forState:UIControlStateNormal];
        bgButton.enabled = NO;
        [bgButton setBackgroundImage:[UIImage imageNamed:@"enButton"] forState:UIControlStateNormal];
    }
}
-(void)leftAction
{
     BOOL isPay = [[NSUserDefaults standardUserDefaults] boolForKey:@"isZCKey"];
    if (isPay) {
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isZCKey"];
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
    else
        [self.navigationController popViewControllerAnimated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
